package com.sunrise.xdoc.view.list;

import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;

import com.sunrise.xdoc.entity.AbstractIdEntity;
import com.sunrise.xdoc.entity.user.User;
import com.sunrise.xdoc.helper.DaoHelper;
import com.sunrise.xdoc.utils.SunriseClassUtils;

/**
 * Data model for the table, with sort and filter header.
 */
public abstract class AbstractListDataModel<T extends AbstractIdEntity> extends LazyDataModel<T> {
	private static final long serialVersionUID = 6827448945103889598L;

	@Autowired
	private DaoHelper daoHelper;

	@Override
	public T getRowData(String rowKey) {
		return daoHelper.getDao(getEntityClass()).findById(Long.valueOf(rowKey));
	}

	@Override
	public Object getRowKey(T entity) {
		return entity.getId();
	}

	@Override
	public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
		DetachedCriteria criteria = daoHelper.getDao(User.class).getDetachedCriteria();
		if (sortField != null) {
			if (sortOrder == SortOrder.ASCENDING) {
				criteria.addOrder(Order.asc(sortField));
			} else if (sortOrder == SortOrder.DESCENDING) {
				criteria.addOrder(Order.desc(sortField));
			}
		}
		for (String filterProperty : filters.keySet()) {
			criteria.add(Restrictions.ilike(filterProperty, filters.get(filterProperty), MatchMode.ANYWHERE));
		}

		List<T> entities = daoHelper.getDao(getEntityClass()).findByCriteria(criteria, first, pageSize);
		this.setRowCount(entities.size());
		return entities;
	}

	@SuppressWarnings("unchecked")
	private Class<T> getEntityClass() {
		return (Class<T>) SunriseClassUtils.getArgumentClass(getClass());
	}
}